package com.smartClassroom.content.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smartClassroom.base.exception.SmartClassroomException;
import com.smartClassroom.base.model.PageParams;
import com.smartClassroom.base.model.PageResult;
import com.smartClassroom.content.mapper.CourseBaseMapper;
import com.smartClassroom.content.mapper.CourseCategoryMapper;
import com.smartClassroom.content.mapper.CourseMarketMapper;
import com.smartClassroom.content.model.dto.*;
import com.smartClassroom.content.model.po.CourseBase;
import com.smartClassroom.content.model.po.CourseMarket;
import com.smartClassroom.content.service.CourseBaseInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {
    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId,PageParams pageParams, QueryCourseParamsDto courseParamsDto) {
        //拼装查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //根据名称模糊查询,在sql中拼接 course_base.name like '%值%'
        queryWrapper.like(org.apache.commons.lang3.StringUtils.isNotEmpty(courseParamsDto.getCourseName()),CourseBase::getName,courseParamsDto.getCourseName());
        //根据课程审核状态查询 course_base.audit_status = ?
        queryWrapper.eq(StringUtils.isNotEmpty(courseParamsDto.getAuditStatus()), CourseBase::getAuditStatus,courseParamsDto.getAuditStatus());
        //todo:按课程发布状态查询
        //根据培训机构id拼装查询条件
        queryWrapper.eq(CourseBase::getCompanyId,companyId);

        //创建page分页参数对象，参数：当前页码，每页记录数
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        //开始进行分页查询
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        //数据列表
        List<CourseBase> items = pageResult.getRecords();
        //总记录数
        long total = pageResult.getTotal();

        //List<T> items, long counts, long page, long pageSize
        PageResult<CourseBase> courseBasePageResult = new PageResult<CourseBase>(items,total,pageParams.getPageNo(), pageParams.getPageSize());
        return  courseBasePageResult;
    }

    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(addCourseDto,courseBase);
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        //审核状态默认为未提交
        courseBase.setAuditStatus("202002");
        //发布状态为未发布
        courseBase.setStatus("203001");
        //保存课程信息
        int insert = courseBaseMapper.insert(courseBase);
        if (insert<0){
            SmartClassroomException.cast("添加课程失败");
        }

        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto,courseMarket);
        Long newCourseId = courseBase.getId();
        courseMarket.setId(newCourseId);

        //保存营销信息
        saveCourseMarket(courseMarket);

        //返回已新增的信息
        CourseBaseInfoDto courseBaseInfoDto = getCourseBaseInfoDto(newCourseId);

        return courseBaseInfoDto;
    }

    @Override
    public CourseBaseInfoDto getCourseBaseById(Long courseId) {
        return  getCourseBaseInfoDto(courseId);
    }

    @Override
    @Transactional
    public CourseBaseInfoDto modifyCourseBase(Long companyId, EditCourseDto editCourseDto) {
        //拿到课程id
        Long courseId = editCourseDto.getId();
        //查询课程信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            SmartClassroomException.cast("课程不存在");
        }

        //数据合法性校验
        //根据具体的业务逻辑去校验
        //本机构只能修改本机构的课程
        if(!companyId.equals(courseBase.getCompanyId())){
            SmartClassroomException.cast("本机构只能修改本机构的课程");
        }

        //封装数据
        BeanUtils.copyProperties(editCourseDto,courseBase);
        //修改时间
        courseBase.setChangeDate(LocalDateTime.now());

        //更新数据库
        int i = courseBaseMapper.updateById(courseBase);
        if(i<=0){
            SmartClassroomException.cast("修改课程失败");
        }
        //更新营销信息
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto,courseMarket);

        saveCourseMarket(courseMarket);
        //查询课程信息
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfoDto(courseId);

        return courseBaseInfo;
    }


    public CourseBaseInfoDto getCourseBaseInfoDto(Long newCourseId) {
        CourseBaseInfoDto courseBaseInfoDto  = new CourseBaseInfoDto();
        CourseBase courseInfo = courseBaseMapper.selectById(newCourseId);
        if (courseInfo==null){
            return null;
        }
        CourseMarket coursemarket = courseMarketMapper.selectById(newCourseId);
        BeanUtils.copyProperties(courseInfo,courseBaseInfoDto);
        if (coursemarket!=null){
            BeanUtils.copyProperties(coursemarket,courseBaseInfoDto);
        }
        courseBaseInfoDto.setMtName(courseCategoryMapper.selectById(courseInfo.getMt()).getName());
        courseBaseInfoDto.setStName(courseCategoryMapper.selectById(courseInfo.getSt()).getName());
        return courseBaseInfoDto;
    }

    private void saveCourseMarket(CourseMarket courseMarket) {
        if (courseMarket.getCharge().equals("201001")) {
            if (courseMarket.getPrice()<=0 || courseMarket.getPrice() == null){
                SmartClassroomException.cast("课程的价格不能为空并且必须大于0");
            }
        }
        CourseMarket market = courseMarketMapper.selectById(courseMarket.getId());
        if (market==null){
            courseMarketMapper.insert(courseMarket);
        }else {
            BeanUtils.copyProperties(courseMarket,market);
            courseMarketMapper.updateById(market);
        }
    }
}
